﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Threading;
using System.ServiceModel;
using System.IO;
using LinqAmazonProvider;  
using Common;
using System.Text;
using System.Globalization;
//using SerchEngine;



namespace LinqAmazonProvider
{
    public class AmazonSearch
    {
        private enum PageLimits {START_PAGE, FINAL_PAGE};
        private Double itemsPerPage = 10;
        private static List<string> ListResult;
        private static ManualResetEvent allDone;
        private static bool firstResult;
        private static int startPage;
        private static int finalPage;
        private static List<string> forbiddenParametersElements = new List<string>(new string[] { "Method", "Skip", "Take", "", "0", "Select", "Language" });

        // Calculate the start and final page to get from amazon
        private int CalcultePagesLimits(Dictionary<string, string> queryParameters, PageLimits pageType) {
            int result = 0;

            if ((queryParameters["Method"] != null) && queryParameters["Method"].Equals("Count"))
            {
                // If method is equal to count, only return the value one, wheter pageType is START OR FINAL
                result = 1;
            }
            else
            {
                if (pageType == PageLimits.START_PAGE)
                {
                    result = 1;
                    if (queryParameters.ContainsKey("Skip"))
                    {
                        int itemsToSkip = int.Parse(queryParameters["Skip"], CultureInfo.InvariantCulture);
                        result += Convert.ToInt32(Math.Floor(Convert.ToDouble(itemsToSkip) / itemsPerPage), CultureInfo.InvariantCulture);

                        queryParameters["Skip"] = (itemsToSkip % 10).ToString(CultureInfo.InvariantCulture);
                    }
                }
                else if (pageType == PageLimits.FINAL_PAGE)
                {
                    result = 10;
                    if (queryParameters.ContainsKey("Take"))
                    {
                        result = startPage + Convert.ToInt32(Math.Ceiling((Double.Parse((queryParameters["Take"]),CultureInfo.InvariantCulture) - 1) / itemsPerPage)) - 1;
                    }
                }
            }
            return (result);
        }

        private static string CreateQueryString(Dictionary<string, string> queryParameters) {
            // Build the REST request
            StringBuilder baseURL = new StringBuilder("http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&SearchIndex=Books&ResponseGroup=Medium");

            foreach (KeyValuePair<string, string> item in queryParameters)
            {
                if (!forbiddenParametersElements.Contains(item.Key) && !forbiddenParametersElements.Contains(item.Value))
                {
                    if (item.Key.Equals("Category"))
                    {
                        baseURL.Append("&").Append("BrowseNode").Append("=").Append(System.Windows.Browser.HttpUtility.UrlEncode(item.Value));
                    }
                    else
                    {
                        baseURL.Append("&").Append(item.Key).Append("=").Append(System.Windows.Browser.HttpUtility.UrlEncode(item.Value));
                    }
                }
            }

            return (baseURL.ToString());
        }

        // Performs the REST search
        public ICollection<string> PerformWebServiceSearch(Dictionary<string, string> parameters)
        {
            ListResult = new List<string>();
            startPage = CalcultePagesLimits(parameters, PageLimits.START_PAGE);
            finalPage = CalcultePagesLimits(parameters, PageLimits.FINAL_PAGE);
            firstResult = true;

            // Set the iterator
            int iteratorValue = startPage;

            // Create a string query based on values in parameters
            string baseURL = CreateQueryString(parameters);

            while (iteratorValue <= finalPage)
            {
                allDone = new ManualResetEvent(false);
                //StringBuilder baseUrlAux = new StringBuilder(baseURL.ToString());
                RestDataAccess da = new RestDataAccess(baseURL + "&ItemPage=" + iteratorValue);
                da.RestRequestCompleted +=new EventHandler<RestRequestCompletedEventArgs>(da_RestRequestCompleted);
                da.PerformRestRequest();
                allDone.WaitOne();
                
                iteratorValue++;
            }
            allDone.Close();
    
            return ListResult;
        }

        static void da_RestRequestCompleted(object sender, RestRequestCompletedEventArgs e)
        {
            //Posible proceso del response
            if (firstResult)
            {
                int totalPages = ResultXmlParser.GetTotalPagesQueryResult(e.Result);
                if (totalPages < finalPage)
                {
                    finalPage = totalPages;
                }
                if (totalPages >= startPage) {
                    ListResult.Add(e.Result);
                }
                firstResult = false;
            }
            else {
                ListResult.Add(e.Result);
            }

            allDone.Set();
        }
    }
}
